package com.l.d.app.library.adapter;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * Created by 林德 on 2017/4/14 11:32.
 * <p/>
 */
public abstract class RvListAdapter<Entity, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    private List<Entity> mList;

    public RvListAdapter() {
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    @Nullable
    public final Entity getItem(int position) {
        return mList == null || position < 0 || position >= getItemCount() ? null : mList.get(position);
    }

    public final RvListAdapter<Entity, VH> add(Entity entity) {
        if (entity == null) return this;
        createListIfNull();
        mList.add(entity);
        notifyDataSetChanged();
        return this;
    }

    public final RvListAdapter<Entity, VH> add(List<Entity> entities) {
        if (entities == null || entities.isEmpty()) return this;
        createListIfNull();
        mList.addAll(entities);
        return this;
    }
    public final RvListAdapter<Entity, VH> add(JSONArray array, Class<Entity> cls) {
        if (array == null || array.isEmpty()) {
            return this;
        }
        createListIfNull();
        if (cls == JSONObject.class) {
            JSONObject object;
            for (int i = 0, size = array.size(); i < size; i++) {
                object = array.getJSONObject(i);
                //noinspection unchecked
                mList.add((Entity) object);
            }
        } else {
            Entity entity;
            for (int i = 0, size = array.size(); i < size; i++) {
                entity = array.getObject(i, cls);
                mList.add(entity);
            }
        }
        return this;
    }
    public final RvListAdapter clear() {
        if (mList != null) {
            mList.clear();
        }
        mList = null;
        return this;
    }

    private void createListIfNull() {
        if (mList == null) {
            mList = onCreateNewEmptyList();
        }
        if (!mList.isEmpty()) {
            mList.clear();
        }
    }

    @NonNull
    public abstract List<Entity> onCreateNewEmptyList();
}
